"use strict";
const mvc = require('cosjs.mvc');
const random = mvc.library.require('random');
/**
 * @name egg
 * 蛋池相关
 */

// /**
//  * @name unlockSit
//  * @param int siteID 位置ID
//  * 解锁孵化器
//  */
// exports.unlockSit = async function () {
//     let siteID = this.get('siteID', 'int');
//     if (!siteID) {
//         return this.quick_error("M2saghge10", "参数缺失siteID");
//     }
//     this.updater.role.key('lv');
//     this.updater.role.key('incubateList');
//     let config = this.config('Incubator', siteID);
//     if (!config) {
//         return this.quick_error("M2saghge40", "消耗配置不存在", siteID);
//     }
//     await this.updater.data();
//     let roleLv = this.updater.role.get('lv');
//     if (roleLv < config.unlockLevel) {
//         return this.quick_error("M2saghge40", "玩家等级不足", roleLv);
//     }
//     let incubateList = this.updater.role.get('incubateList');
//     if (incubateList[siteID] != undefined) {
//         return this.quick_error("M2saghge40", "该位置已经解锁", siteID);
//     }
//     this.updater.sub(config.costItem, config.costNum);
//     var obj = new Object();
//     obj.eggID = "";
//     obj.beginTime = "";

//     incubateList[siteID] = obj;
//     this.updater.role.set('incubateList', incubateList)
//     return this.updater.save();
// }

// @param json player 玩家:阵容，机器人前面加‘z’

/**
 * @name setEgg
 * @param json egg  siteID位置ID:eggID
 * 把蛋放到孵化器上
 */
exports.setEgg = async function () {
    let eggData = this.get('egg', 'json');
    if (!eggData) {
        return this.quick_error('M2saghge140', ' 参数错误');
    }
    this.updater.role.key('incubateList');
    await this.updater.data();
    let incubateList = this.updater.role.get('incubateList');
    this.updater.item.sub(parseInt(eggData.eggID), 1);
    if (incubateList[eggData.siteID] == undefined) {
        return this.quick_error('M2saghge140', '该位置不可使用', eggData.siteID);
    }
    if (incubateList[eggData.siteID].eggID && incubateList[eggData.siteID].eggID != '') {
        return this.quick_error('M2saghge140', '该位置不可使用', incubateList[eggData.siteID].eggID);
    }
    incubateList[eggData.siteID].eggID = eggData.eggID
    incubateList[eggData.siteID].beginTime = Date.now();
    this.updater.role.set('incubateList', incubateList)
    return this.updater.save();
}

/**
 * @name openEgg
 * @param int siteID
 * 开蛋
 */
exports.openEgg = async function () {
    let siteID = this.get('siteID', 'int');
    if (!siteID) {
        return this.quick_error('M2saghge140', ' 参数错误');
    }
    this.updater.role.key('incubateList');
    await this.updater.data();
    let incubateList = this.updater.role.get('incubateList');
    let eggID = incubateList[siteID].eggID;
    let sumTime = Date.now() - incubateList[siteID].beginTime;
    incubateList[siteID].beginTime = '';
    incubateList[siteID].eggID = '';
    this.updater.role.set('incubateList', incubateList)
    let eggConfig = this.config('egg', eggID);
    if (!eggConfig) {
        return this.quick_error("M2saghge40", "角色数据不存在", eggID);
    }
    if (sumTime < eggConfig.time * 1000) {
        return this.quick_error("M2saghge40", "开蛋条件不满足", eggID);
    }
    this.updater.record.add(38, 1);
    this.updater.daily.add("record." + 38, 1);
    this.updater.item.add(eggConfig.itemGroup, 1)
    // this.updater.item.sub(parseInt(eggID), 1);
    return this.updater.save();
}

/**
 * @name boostEgg
 * @param int siteID
 * 孵化加速
 */
exports.boostEgg = async function () {
    let siteID = this.get('siteID', 'int');
    if (!siteID) {
        return this.quick_error('M2saghge140', ' 参数错误');
    }
    this.updater.role.key('incubateList');
    await this.updater.data();
    let incubateList = this.updater.role.get('incubateList');
    let eggID = incubateList[siteID].eggID;
    let eggConfig = this.config('egg', eggID);
    if (!eggConfig) {
        return this.quick_error("M2saghge40", "角色数据不存在", eggID);
    }
    incubateList[siteID].beginTime -= eggConfig.time * 1000;
    this.updater.role.set('incubateList', incubateList)
    this.updater.item.sub(60600003, 1);
    return this.updater.save();
}

/**
 * @name getEggPool
 * @param string id 蛋池ID
 * 拉蛋池数据
 */
exports.getEggPool = async function () {
    let id = this.get('id', 'string');
    if (!id) {
        return this.error('id empty')
    }
    let incubatorEggBuildId = this.config('base', 'collectBuild_PlayerBagBigger').val;
    if (!incubatorEggBuildId) {
        return this.quick_error('建筑配置不存在');
    }
    this.updater.role.key('buildingsInfo.' + incubatorEggBuildId);
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + incubatorEggBuildId) || { "level": 0 };
    let eggBuildConfig = this.config('incubatorEggBuild', buildData.level);
    if (!eggBuildConfig) {
        return this.quick_error('蛋池扩充配置不存在', buildData.level);
    }
    if (id != eggBuildConfig.poolId && id <= 100) {
        return this.quick_error('该蛋池ID与当前蛋池ID不一致', id, "config:" + eggBuildConfig.poolId);
    }
    this.eggPool = this.model.mongo("eggPool", this.sid, this.uid);

    //   //DEBUG
    //   this.collect = this.model.mongo("collect",this.sid,this.uid);
    //   //  this.collect.apply(this.uid,id,type,val).then(()=>obj);
    //   this.collect.apply(this.uid,1001,3,1).then(()=>obj);
    //  let ret = await this.collect.mget(1);

    return this.eggPool.uget(this.uid, id).then(r => {
        if (r) {
            //TODO 验证蛋池是不是只剩下石头
            let costList = this.config('base', 'refreshEggPool').strVal.split(',');
            let num = 0
            for (let i in r.itemList) {
                // console.log(i + " = " + r.itemList[i]);
                for (let k = 0; k < costList.length; k++) {
                    if (i != costList[k]) {
                        num += r.itemList[i]
                    }
                }
            }
            if (num == 0) {
                // return null
            } else {
                return r
            }
        }
        else {
            return null
        }
    }).then(async r => {
        if (!r) {
            //更新蛋池 catcherPool
            let config = this.config("catcherPool", id);
            // let itemGroup = mvc.config('catcherPool', id);
            // let arr = Array.isArray(itemGroup) ? itemGroup : itemGroup['rows'] || itemGroup['Coll'];
            if (!config) {
                return this.quick_error("M2HS3", "蛋池数据不存在", id);
            }
            var obj = new Object();
            var ifEgg = 0;
            this.updater.role.set("eggPoolID", id);
            for (let i = 0; i < config.Coll.length; i++) {
                let poolData = config.Coll[i]
                let groupID = poolData.groupId;
                let k = random.Relative(poolData.proGroup, 'pro');
                if (k === false || !poolData.proGroup[parseInt(k)]) {
                    continue
                    return this.quick_error("M2HS4", "蛋池数据不匹配");
                }
                if (poolData.ifEgg && poolData.proGroup[parseInt(k)].num != 0) {
                    ifEgg = 1;
                }
                if (config.Coll[i].numPerWeek) {
                    //有每周限制
                    // let today = this.library("time/week");
                    let dkey = "eggPool." + config.Coll[i].poolId + "." + config.Coll[i].groupId;
                    let data = await this.updater.daily.model.week(dkey);
                    let v = data[dkey] || 0;
                    let m = config.Coll[i].numPerWeek - v;
                    if (m > 0) {
                        if (obj[groupID]) {
                            if (m - poolData.proGroup[parseInt(k)].num < 0) {
                                obj[groupID] += m;
                            } else {
                                obj[groupID] += poolData.proGroup[parseInt(k)].num;
                            }
                        } else {
                            if (m - poolData.proGroup[parseInt(k)].num < 0) {
                                obj[groupID] = m;
                            } else {
                                obj[groupID] = poolData.proGroup[parseInt(k)].num;
                            }
                        }
                    } else {
                        //这里应该替换成啥呢
                    }
                } else {
                    if (obj[groupID]) {
                        obj[groupID] += poolData.proGroup[parseInt(k)].num
                    } else {
                        obj[groupID] = poolData.proGroup[parseInt(k)].num
                    }
                }
                // if (obj[groupID]) {
                //     obj[groupID] += poolData.proGroup[parseInt(k)].num
                // } else {
                //     obj[groupID] = poolData.proGroup[parseInt(k)].num
                // }
            }
            if (!ifEgg) {
                //从表里roll一个蛋出来
                let costConfig = this.config("catcherPoolConfig", id);
                if (!costConfig) {
                    return this.quick_error("M2saghge40", "消耗配置不存在", id);
                }
                if (costConfig.guaranteedEggGroup) {
                    var array = costConfig.guaranteedEggGroup.split(',');
                    //从array里随机一个
                    // var randomIndex = Math.floor(Math.random() * array.length);
                    // var randomValue = array[randomIndex];
                    obj[parseInt(array[Math.roll(0, array.length - 1)])] = 1;
                }
            }
            // return this.eggPool.apply(this.uid,id,obj).then(()=>1);
            return this.eggPool.apply(this.uid, id, obj).then(() => obj);
        } else {
            //DEBUG

            // this.collect = this.model.mongo("collect",this.sid,this.uid);
            // //  this.collect.apply(this.uid,id,type,val).then(()=>obj);
            // this.collect.apply(this.uid,1005,3,1).then(()=>obj);
            // this.collect.apply(this.uid,1004,3,1).then(()=>obj);
            // this.collect.apply(this.uid,1003,1,1).then(()=>obj);
            return r.itemList;
        }
    })
}

/**
 * @name refreshEggPool
 * @param string id 蛋池ID
 * 刷新蛋池数据
 */
exports.refreshEggPool = async function () {
    let id = this.get('id', 'string');
    if (!id) {
        return this.error('id empty')
    }

    let incubatorEggBuildId = this.config('base', 'collectBuild_PlayerBagBigger').val;
    if (!incubatorEggBuildId) {
        return this.quick_error('建筑配置不存在');
    }
    this.updater.role.key('buildingsInfo.' + incubatorEggBuildId);
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + incubatorEggBuildId) || { "level": 0 };
    let eggBuildConfig = this.config('incubatorEggBuild', buildData.level);
    if (!eggBuildConfig) {
        return this.quick_error('蛋池扩充配置不存在', buildData.level);
    }
    if (id != eggBuildConfig.poolId && id <= 100) {
        return this.quick_error('该蛋池ID与当前蛋池ID不一致', id, "config:" + eggBuildConfig.poolId);
    }
    this.eggPool = this.model.mongo("eggPool", this.sid, this.uid);
    //更新蛋池 catcherPool
    let config = this.config("catcherPool", id);
    this.updater.role.set("eggPoolID", id);
    // let itemGroup = mvc.config('catcherPool', id);
    // let arr = Array.isArray(itemGroup) ? itemGroup : itemGroup['rows'] || itemGroup['Coll'];
    if (!config) {
        return this.quick_error("M2HS3", "蛋池数据不存在", id);
    }
    let costConfig = this.config("catcherPoolConfig", id);
    if (!costConfig) {
        return this.quick_error("M2saghge40", "消耗配置不存在", id);
    }
    //判断是不是刷新的物品ID
    this.updater.item.sub(costConfig.refreshCost, costConfig.refreshCostNum);

    //需要拿到本周的蛋池数量限制
    var obj = new Object();
    var ifEgg = 0;
    for (let i = 0; i < config.Coll.length; i++) {
        let poolData = config.Coll[i]
        let groupID = poolData.groupId;
        let k = random.Relative(poolData.proGroup, 'pro');
        if (k === false || !poolData.proGroup[parseInt(k)]) {
            continue;
            return this.quick_error("M2HS4", "蛋池数据不匹配");
        }
        if (poolData.ifEgg && poolData.proGroup[parseInt(k)].num != 0) {
            ifEgg = 1;
        }
        if (config.Coll[i].numPerWeek) {
            //有每周限制
            // let today = this.library("time/week");
            let dkey = "eggPool." + config.Coll[i].poolId + "." + config.Coll[i].groupId;
            let data = await this.updater.daily.model.week(dkey);
            let v = data[dkey] || 0;
            let m = config.Coll[i].numPerWeek - v;
            if (m > 0) {
                if (obj[groupID]) {
                    if (m - poolData.proGroup[parseInt(k)].num < 0) {
                        obj[groupID] += m;
                    } else {
                        obj[groupID] += poolData.proGroup[parseInt(k)].num;
                    }
                } else {
                    if (m - poolData.proGroup[parseInt(k)].num < 0) {
                        obj[groupID] = m;
                    } else {
                        obj[groupID] = poolData.proGroup[parseInt(k)].num;
                    }
                }
            } else {
                //这里应该替换成啥呢
            }
        } else {
            if (obj[groupID]) {
                obj[groupID] += poolData.proGroup[parseInt(k)].num
            } else {
                obj[groupID] = poolData.proGroup[parseInt(k)].num
            }
        }
    }
    if (!ifEgg) {
        //从表里roll一个蛋出来
        if (costConfig.guaranteedEggGroup) {
            var array = costConfig.guaranteedEggGroup.split(',');
            //从array里随机一个
            // var randomIndex = Math.floor(Math.random() * array.length);
            // var randomValue = array[randomIndex];
            // obj[parseInt(array[randomIndex])] = 1;
            obj[parseInt(array[Math.roll(0, array.length - 1)])] = 1;
        }
    }
    // return this.eggPool.apply(this.uid,id,obj).then(()=>1);
    await this.updater.save();
    return this.eggPool.apply(this.uid, id, obj).then(() => obj);
}

/**
 * @name catchEgg
 * @param string id 蛋池ID
 * @param int catchId 爪子ID
 * @param json rewardData  物品ID:数量
 * 抓蛋奖励
 */
exports.catchEgg = async function () {
    let id = this.get('id', 'string');
    if (!id) {
        return this.error('id empty')
    }
    let rewardData = this.get('rewardData', 'json');
    if (!rewardData) {
        return this.quick_error('M2saghge140', ' 参数错误');
    }
    let catchId = this.get('catchId', 'int');
    if (!catchId) {
        return this.error('id empty')
    }

    this.eggPool = this.model.mongo("eggPool", this.sid, this.uid);
    let model = this.model.mongo("item", this.sid, this.uid);
    let number = await model.mcount(90);
    if (number >= mvc.config('base', 'eggTaskMaxNum').val) {
        await model.mdel(90);
    }
    let maxTaskReward = this.config('base', 'eggTaskMaxNumExchange').strVal.split(':');
    return this.eggPool.uget(this.uid, id).then(async r => {
        let changeNum = 0;
        let catchConfig = this.config("catcherConfig", catchId);
        if (!catchConfig) {
            return this.quick_error("M2HS3", "钩子数据不存在", catchId);
        }
        //通过catchID拿itemID
        let costID = 0, costNum = 0;
        // this.updater.item.key(catchConfig.catcherId)
        await this.updater.data();
        // let catachNum = this.updater.item.get(catchConfig.catcherId);
        // console.log("剩余爪子数量：", catchConfig.catcherId,catachNum);
        // let flag = 0;
        // if (catachNum) {
        //     if (catachNum.val > 0) {
        //         flag = 1;
        //     }
        // }
        // if (flag) {
        //     costID = catchConfig.catcherId;
        //     costNum = 1;
        //     this.updater.item.sub(costID, costNum);
        // } else {
        costID = catchConfig.costItem;
        costNum = catchConfig.costNum;
        for (var k in catchConfig.itemCost) {
            if (catchConfig.itemCost[k].num != 0) {
                this.updater.item.sub(catchConfig.itemCost[k].id, catchConfig.itemCost[k].num);
            }
        }
        // }
        // this.updater.item.sub(catchConfig.fuelID, catchConfig.fuelCost);
        let _total_add = {};
        if (r) {
            for (let itemID in rewardData) {
                if ((r.itemList[itemID] - parseInt(rewardData[itemID])) >= 0) {
                    r.itemList[itemID] -= parseInt(rewardData[itemID]);
                    for (let i = 0; i < parseInt(rewardData[itemID]); i++) {
                        // console.log("itemID:", itemID);
                        // console.log("rewardData[itemID]:", rewardData[itemID]);
                        //每日计数
                        let dkey = "eggPool." + id + "." + itemID;
                        this.updater.daily.add(dkey, rewardData[itemID]);
                        let { err, ret } = this.library("item/group", itemID, rewardData[itemID]);
                        if (err) {
                            return this.error(err, ret);
                        }
                        // console.log("ret:", ret);
                        if (Array.isArray(ret)) {
                            for (let v in ret) {
                                if (_total_add.hasOwnProperty(ret[v].id)) {
                                    _total_add[ret[v].id] += ret[v].num;
                                } else {
                                    _total_add[ret[v].id] = ret[v].num;
                                }
                            }
                        } else {
                            if (_total_add.hasOwnProperty(ret.id)) {
                                _total_add[ret.id] += ret.num;
                            } else {
                                _total_add[ret.id] = ret.num;
                            }
                        }
                        // this.updater.item.group(itemID,rewardData[itemID]);
                    }
                }
            }
            this.eggPool.apply(this.uid, id, r.itemList)
            if (id < 100) {
                this.updater.record.add(16, 1);
                this.updater.daily.add("record." + "16", 1);
            }


            // console.log("number:", number);
            // console.log("mvc.config('base', 'eggTaskMaxNum').val:", mvc.config('base', 'eggTaskMaxNum').val);
            for (let i in _total_add) {
                // this.updater.add(parseInt(i), _total_add[i]);
                if (this.updater.iTypes(parseInt(i)).bag == 90) {
                    if (number >= mvc.config('base', 'eggTaskMaxNum').val) {
                        changeNum++;
                        this.updater.add(parseInt(maxTaskReward[0]), parseInt(maxTaskReward[1]));
                    } else {
                        this.updater.add(parseInt(i), _total_add[i]);
                        number += _total_add[i];
                    }
                } else {
                    this.updater.add(parseInt(i), _total_add[i]);
                }
            }


            await this.updater.save();
            return { "changeNum": changeNum };
        }
        else {
            return this.quick_error('M2saghge140', ' 参数错误');
        }
    })
}


/**
 * @name shakeEggPool
 * @param string id 蛋池ID
 * 抖下蛋池
 */
exports.shakeEggPool = async function () {
    let id = this.get('id', 'string');
    if (!id) {
        return this.error('id empty')
    }
    let config = this.config("catcherPoolConfig", id);
    if (!config) {
        return this.quick_error("M2saghge40", "消耗配置不存在", id);
    }
    //判断是不是刷新的物品ID
    this.updater.item.sub(config.shakeCost, config.shakeCostNum);
    return this.updater.save();
}


/**
 * @name refreshStonePool
 * @param string id 蛋池ID
 * 刷新只剩下石头的蛋池
 */
exports.refreshStonePool = async function () {
    let id = this.get('id', 'string');
    if (!id) {
        return this.error('id empty')
    }

    let incubatorEggBuildId = this.config('base', 'collectBuild_PlayerBagBigger').val;
    if (!incubatorEggBuildId) {
        return this.quick_error('建筑配置不存在');
    }
    this.updater.role.key('buildingsInfo.' + incubatorEggBuildId);
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + incubatorEggBuildId) || { "level": 0 };
    let eggBuildConfig = this.config('incubatorEggBuild', buildData.level);
    if (!eggBuildConfig) {
        return this.quick_error('蛋池扩充配置不存在', buildData.level);
    }
    if (id != eggBuildConfig.poolId && id <= 100) {
        return this.quick_error('该蛋池ID与当前蛋池ID不一致', id, "config:" + eggBuildConfig.poolId);
    }

    this.eggPool = this.model.mongo("eggPool", this.sid, this.uid);
    return this.eggPool.uget(this.uid, id).then(r => {
        if (r) {
            //TODO 验证蛋池是不是只剩下石头
            let costList = this.config('base', 'refreshEggPool').strVal.split(',');
            let num = 0
            for (let i in r.itemList) {
                var flag = 0;
                for (let k = 0; k < costList.length; k++) {
                    if (i == costList[k]) {
                        flag = 1;
                        // num+=r.itemList[i];
                        // break;
                    }
                }
                if (!flag) {
                    num += r.itemList[i];
                }
            }
            if (num == 0) {
                return null
            } else {
                return r
            }
        }
        else {
            return null
        }
    }).then(r => {
        if (!r) {
            //更新蛋池 catcherPool
            let config = this.config("catcherPool", id);
            if (!config) {
                return this.quick_error("M2HS3", "蛋池数据不存在", id);
            }
            this.updater.role.set("eggPoolID", id);
            var obj = new Object();
            var ifEgg = 0;
            for (let i = 0; i < config.Coll.length; i++) {
                let poolData = config.Coll[i]
                let groupID = poolData.groupId;
                let k = random.Relative(poolData.proGroup, 'pro');
                if (k === false || !poolData.proGroup[parseInt(k)]) {
                    continue;
                    return this.quick_error("M2HS4", "蛋池数据不匹配");
                }
                if (poolData.ifEgg && poolData.proGroup[parseInt(k)].num != 0) {
                    ifEgg = 1;
                }
                if (obj[groupID]) {
                    obj[groupID] += poolData.proGroup[parseInt(k)].num
                } else {
                    obj[groupID] = poolData.proGroup[parseInt(k)].num
                }
            }
            if (!ifEgg) {
                //从表里roll一个蛋出来
                let costConfig = this.config("catcherPoolConfig", id);
                if (!costConfig) {
                    return this.quick_error("M2saghge40", "消耗配置不存在", id);
                }
                if (costConfig.guaranteedEggGroup) {
                    var array = costConfig.guaranteedEggGroup.split(',');
                    //从array里随机一个
                    // var randomIndex = Math.floor(Math.random() * array.length);
                    // var randomValue = array[randomIndex];
                    // obj[parseInt(array[randomIndex])] = 1;
                    obj[parseInt(array[Math.roll(0, array.length - 1)])] = 1;
                }
            }
            return this.eggPool.apply(this.uid, id, obj).then(() => obj);
        } else {
            return r.itemList;
        }
    })
}
